﻿<%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="forums_default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ import Namespace="RobozzleModel" %>
<%@ Import Namespace="System.Linq" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>RoboZZle Forums</title>
    <link href="../stats.css" rel="stylesheet" type="text/css"/>
</head>
<body>

<%= StatsCommon.MenuBar(MenuPage.Forums) %>
<h1>RoboZZle Forums</h1>
<%
    RobozzleEntities entities = new RobozzleEntities();
    entities.Refresh(System.Data.Objects.RefreshMode.StoreWins, entities.ForumCategory);    
    entities.Refresh(System.Data.Objects.RefreshMode.StoreWins, entities.ForumThread);
    entities.Refresh(System.Data.Objects.RefreshMode.StoreWins, entities.ForumComment);

    int categoryId;
    if (!int.TryParse(Request["category"], out categoryId)) categoryId = -1;

    // Are we creating a new thread?
    string userArg = Request.Params["user"];
    string passwordArg = Request.Params["password"];
    string newThreadArg = Request.Params["newthread"];
    bool invalidPwd = false;
    bool newThreadSuccess = false;

    if (categoryId != -1 && newThreadArg != null)
    {
        ForumCategory category = entities.ForumCategory.Where(c => c.Id == categoryId).FirstOrDefault();
        if (category != null)
        {
            passwordArg = StatsCommon.HashPassword(passwordArg);
            if (entities.User.Any(user => user.Username == userArg && user.Password == passwordArg))
            {
                entities.AddToForumThread(
                    new ForumThread
                    {
                        DateOpened = DateTime.Now,
                        ForumCategory = category,
                        IpAddress = Request.UserHostAddress,
                        OpenedBy = userArg,
                        ThreadTitle = newThreadArg,
                    });

                entities.SaveChanges();
                newThreadSuccess = true;
                newThreadArg = null;
            }
            else
            {
                invalidPwd = true;
            }
        }
    }
    
    // Write the breadcrumb path
    if (categoryId != -1)
    {
        ForumCategory category = entities.ForumCategory.Where(c => c.Id == categoryId).First();
        if (category != null)
        {
            Response.Write("<p>" + StatsCommon.MakeForumPath(categoryId, category.Title, null) + "</p>");
        }
    }
    

    if (invalidPwd)
    {
        Response.Write("<p style=\"color:#e88\">Invalid username / password.</p>");
    }
    else if (newThreadSuccess)
    {
        Response.Write("<p style=\"color:#aea\">Thread created.</p>");
    }

    foreach (var category in entities.ForumCategory)
    {
        // If we are only showing a specific category, skip all other categories
        if (categoryId != -1 && categoryId != category.Id) continue;
        
%>

<div class="threadList" style="margin-left:auto; margin-right:auto; width:800px; border: solid 1px black;">
<p style="text-align:left; margin:20px 20px 5px 20px">
    <strong><%= category.Title %></strong>&nbsp; <a href="/forums/default.aspx?category=<%=category.Id %>">(<%= StatsCommon.Plural("thread", category.ForumThread.Count) %>)</a>
    <% if (category.Id != PUZZLE_CATEGORY && categoryId==-1) { %> &nbsp; <a href="/forums/default.aspx?category=<%=category.Id %>#new">New thread</a> <% } %>    
</p>
<p style="text-align:left; margin: 0 0 0 20px; font-size: small"><%= category.Description %></p>
<table style="margin: 10px; table-layout: fixed;">
<thead>
<tr>
    <th style="text-align:left; width: 400px">Title</th>
    <th style="width: 100px">Comments</th> 
    <th style="width: 200px" colspan="2">Last comment</th>
</tr>
</thead>
    <%
        System.Collections.Generic.IEnumerable<ForumThread> threads;

        int maxThreads = 10;
        if (categoryId == -1)
        {
            threads = category.ForumThread
                .Where(thread => thread.ForumComment.Count > 0)
                .OrderByDescending(thread => thread.ForumComment.Max(comment => comment.Date))
                .Take(maxThreads).ToArray();
        }
        else
        {
            threads = category.ForumThread;
        }

        var threadsToShow = from t in threads
                            select new { Thread = t, LastComment = t.ForumComment.OrderByDescending(comment => comment.Date).FirstOrDefault() };
        
        OddEven oe = new OddEven();
        int threadsShown = 0;
        foreach (var thread in threadsToShow.OrderByDescending(t => t.LastComment == null ? DateTime.MinValue : t.LastComment.Date))
        {
            threadsShown++;
            var lastComment = thread.LastComment;
            string rowClass = oe.Next() + "Row";
    %>

    <tr>
        <td class="<%=rowClass %>" style="text-align:left"><%= StatsCommon.ThreadLink(thread.Thread, Server.HtmlEncode(thread.Thread.ThreadTitle)) %></td>    
        <td class="<%=rowClass %>"><%= thread.Thread.ForumComment.Count() %></td>
        <td class="<%=rowClass %>" style="width: 100px"><%= lastComment == null ? "" : StatsCommon.FormatDate(lastComment.Date) %></td>
        <td class="<%=rowClass %>" style="text-align:left"><%= lastComment == null ? "" : StatsCommon.UserLink(lastComment.UserName)%></td>
    </tr>            
            
    <%
        }
    %>
    </table>
    
    <!-- Show the "Remaining threads" link -->
    <% if (threadsShown == maxThreads && categoryId==-1) { %>
        <p style="text-align:left; margin: 0px 20px 20px 20px; font-size: small;">
            <a href="/forums/default.aspx?category=<%=category.Id %>">... Remaining threads ...</a>
        </p>
    <% } %>
    
    </div>     
    <p>&nbsp;</p>      
<%        
    } // foreach(category)
%>

<%
    // Show a form to create threads
    // Do not allow users to create threads under the "Puzzle" category
    if (categoryId != -1 && categoryId != PUZZLE_CATEGORY)
    {
        %>
        <a name="new"></a>
        <form name="newThread" action="" method="post">
        <div class="forumForm" style="width:300px">
            <p style="margin-top:3px; margin-bottom:3px;"><strong>Create a new thread</strong></p>
            <table width="300px">
                <tr>
                    <td style="width:60px;text-align: left;">User:</td>
                    <td style="text-align:left"><input name="user" maxlength="20" style="width:190px" type="text" value="<%= Server.HtmlEncode(userArg) %>"/></td>
                </tr>
                <tr>
                    <td style="width:60px;text-align: left;">Password:</td>
                    <td><input name="password" type="password" style="width:190px"/></td>
                </tr>
                <tr>
                    <td style="width:60px;text-align: left;">Topic:</td>
                    <td style="text-align:left"><input name="newthread" maxlength="100" style="width:190px" type="text" value="<%= Server.HtmlEncode(newThreadArg) %>" /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" style="margin-top:10px" value="Create thread"/></td>
                </tr>
            </table>
        </div>
        </form>
        
        <%
    }
%>


<%
     Response.Write(StatsCommon.Footer());
%>
</body>
</html>
